package com.stt.base.service;

import com.stt.base.model.TimerTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 定时任务服务类
 */
@Service
public class TimerTaskService {
    
    @Autowired
    private DeviceService deviceService;
    
    // 模拟定时任务存储
    private final Map<Long, TimerTask> taskMap = new ConcurrentHashMap<>();
    private Long taskIdCounter = 1L;
    
    /**
     * 创建定时任务
     */
    public TimerTask createTask(TimerTask task) {
        task.setId(taskIdCounter++);
        taskMap.put(task.getId(), task);
        return task;
    }
    
    /**
     * 获取所有定时任务
     */
    public List<TimerTask> getAllTasks() {
        return new ArrayList<>(taskMap.values());
    }
    
    /**
     * 删除定时任务
     */
    public void deleteTask(Long id) {
        taskMap.remove(id);
    }
    
    /**
     * 定时检查和执行任务
     * 每分钟执行一次
     */
    @Scheduled(fixedRate = 60000)
    public void checkAndExecuteTasks() {
        LocalDateTime now = LocalDateTime.now();
        
        for (TimerTask task : new ArrayList<>(taskMap.values())) {
            if (task.getExecuteTime().isBefore(now) || task.getExecuteTime().equals(now)) {
                // 执行任务
                deviceService.controlDeviceStatus(task.getDeviceId(), task.isTargetStatus());
                deviceService.controlDeviceParameter(task.getDeviceId(), task.getTargetParameter());
                
                // 处理重复任务
                if (task.isRepeat()) {
                    // 更新下次执行时间
                    task.setExecuteTime(task.getExecuteTime().plusMinutes(task.getRepeatInterval()));
                } else {
                    // 非重复任务执行完后删除
                    taskMap.remove(task.getId());
                }
            }
        }
    }
} 